package sharetime.web.controllers;

import java.util.List;

@SuppressWarnings("unchecked")
public class PaginationSupport {
	
	private List items;
	private int startIndex;
	private int countOnEachPage;
	public static int DEFAULT_COUNT_ON_EACH_PAGE = 10;
	private int total;

	public PaginationSupport() {
		this(DEFAULT_COUNT_ON_EACH_PAGE);
	}

	public PaginationSupport(int countOnEachPage) {
		startIndex = 0;
		total = -1;
		if (countOnEachPage < 1) {
			throw new IllegalArgumentException(
					"Count should be greater than zero!");
		} else {
			this.countOnEachPage = countOnEachPage;
			return;
		}
	}

	public int getCountOnEachPage() {
		return countOnEachPage;
	}

	public List getItems() {
		return items;
	}

	public void setItems(List items) {
		this.items = items;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public int getEndIndex() {
		int endIndex = getStartIndex() + countOnEachPage;
		if (endIndex > getTotal())
			return getTotal();
		else
			return endIndex;
	}

	public int getStartIndex() {
		if (startIndex > getTotal())
			return getTotal();
		if (startIndex < 0)
			return 0;
		else
			return startIndex;
	}

	public int getStartIndexValue() {
		return startIndex;
	}

	public int getNextIndex() {
		return getNextStartIndexes()[0];
	}

	public int getPreviousIndex() {
		int previousIndexes[] = getPreviousStartIndexes();
		return previousIndexes[previousIndexes.length - 1];
	}

	public int[] getNextStartIndexes() {
		int index = getEndIndex();
		if (index == getTotal())
			return null;
		int count = (getTotal() - index) / countOnEachPage;
		if ((getTotal() - index) % countOnEachPage > 0)
			count++;
		int result[] = new int[count];
		for (int i = 0; i < count; i++) {
			result[i] = index;
			index += countOnEachPage;
		}

		return result;
	}

	public int[] getPreviousStartIndexes() {
		int index = getStartIndex();
		if (index == 0)
			return null;
		int count = index / countOnEachPage;
		if (index % countOnEachPage > 0)
			count++;
		int result[] = new int[count];
		for (int i = count - 1; i > 0; i--) {
			index -= countOnEachPage;
			result[i] = index;
		}

		return result;
	}

	public int getNiceStartIndex() {
		return getStartIndex() + 1;
	}

	public List getPage() {
		return getItems().subList(getStartIndex(), getEndIndex());
	}

	public int getTotal() {
		if (items != null)
			return items.size();
		else
			return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

}
